# coding:utf-8 
# 下载图片
# 引入requests包和正则表达式包re
import requests
import re,os,time
 
# 自定义下载页面函数
def load_page(url):
    response=requests.get(url)
    data=response.content
    return data
 
# 自定义保存页面图片函数
def get_image(html):
    regx=r'http://[\S]*jpg'  # 定义图片正则表达式
    pattern=re.compile(regx) # 编译表达式构造匹配模式
    get_images=re.findall(pattern,repr(html)) # 在页面中匹配图片链接
 
    num=1
    # 遍历匹配成功的链接
    for img in  get_images:
        image=load_page(img) #根据图片链接，下载图片链接
        # 将下载的图片保存到对应的文件夹中
        proDir = os.path.split(os.path.realpath(__file__))[0]
        picDir = os.path.join(proDir,'pic')
        with open(picDir+'%s.jpg' % num,'wb') as fb:
            fb.write(image)
            print("正在下载第%s张图片" %num)
            num=num+1
    print("下载完成！")
num = 1
proDir = os.path.split(os.path.realpath(__file__))[0]
picDir = os.path.join(proDir,'pic')
code = '1434694'
# picDir = os.path.join(picDir,code)
totals = 719
data = bytes()
# 定义爬取页面的链接
for i in range(314,totals+1):
    url ='https://i0.nyacdn.com/galleries/'+code+'/'+str(i)+'.jpg'
    # 调用load_page函数，下载页面内容
    try:
        data = load_page(url)
    except Exception as err:
	    i = i-1
    finally:
    	with open(picDir+'/'+code+'-'+str(i)+'.jpg','wb') as fb:
            fb.write(data)
            print("正在下载第%s张" %i + time.strftime('%m-%d %H:%M:%S', time.localtime(time.time())))